<script>
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
    data() {
        return {
            localWgtInfo: {},
            serverWgtInfo: {},
            platform: ''
        }
    },
    computed: {
        ...mapState(['locale'])
    },
    onLaunch: function() {
        this.getUserInfo()
        this.get_locale()
        this.$i18n.locale = this.locale
    },
    methods: {
        ...mapMutations(['login', 'logout', 'setToken']),
        ...mapActions(['get_token', 'get_locale']),
        async init() {
            // #ifdef APP-PLUS
            this.updateApp()
            // #endif
            // await this.getIndexInfo()
            // await this.getUserInfo()
        },
        // async getIndexInfo() {
        //     await this.get_token()
        //     const res = await this.$http('get|api/Index/index')
        //     this.setToken(res.result.session_id)
        // },
        getUserInfo() {
            this.$store.dispatch('getUserInfo')
        },
        async updateApp() {
            if (this.updateStatus) {
                return
            }
            this.updateStatus = true
            const url = 'https://www.global3pro.com/api/Index/app_version'
            const res = await this.$http(`get|${url}`)
            // const res = await this.$http('get|api/Index/app_version')
            this.serverWgtInfo = res.result.version
            this.platform = uni.getSystemInfoSync().platform
            console.log('this.serverWgtInfo', this.serverWgtInfo)
            plus.runtime.getProperty(plus.runtime.appid, wgtinfo => {
                this.localWgtInfo = wgtinfo
                let update = [false, false, false]
                if (this.platform === 'ios') {
                    update = this.isUpdate(this.localWgtInfo.version, this.serverWgtInfo.ios_version)
                } else if (this.platform === 'android') {
                    update = this.isUpdate(this.localWgtInfo.version, this.serverWgtInfo.app_version)
                }
                let isUpdate = update.find(x => x === true)
                console.log('isUpdate', isUpdate)
                if (isUpdate) {
                    this.showUpdate(update)
                } else {
                    this.updateStatus = false
                }
            })
        },
        showUpdate(update) {
            uni.showModal({
                title: '系统升级',
                content: this.serverWgtInfo.app_log,
                showCancel: false,
                success: res => {
                    if (res.confirm) {
                        if (update[0] || update[1]) {
                            // 大更新
                            if (this.platform === 'ios') {
                                // https://apps.apple.com/cn/app/nv%E6%96%B0%E8%A7%86%E7%95%8C/id1600812817
                                plus.runtime.openURL(this.serverWgtInfo.ios_url)
                            } else if (this.platform === 'android') {
                                plus.runtime.openURL(this.serverWgtInfo.android_url)
                            }
                            this.updateStatus = false
                        } else if (update[2]) {
                            // 小更新
                            const host = 'https://www.global3pro.com'
                            this.createDownload(host + this.serverWgtInfo.hot_update)
                            // this.createDownload(this.$store.state.$image + this.serverWgtInfo.hot_update)
                        }
                    }
                }
            })
        },
        isUpdate(curVersion, serVersion) {
            // 判断是否需要更新
            curVersion = curVersion.split('.').map(x => parseInt(x))
            serVersion = serVersion.split('.').map(x => parseInt(x))
            let result = [false, false, false]
            if (serVersion[0] > curVersion[0]) {
                result = [true, false, false]
            } else if (serVersion[0] === curVersion[0] && serVersion[1] > curVersion[1]) {
                result = [false, true, false]
            } else if (serVersion[1] === curVersion[1] && serVersion[2] > curVersion[2]) {
                result = [false, false, true]
            }
            return result
        },
        createDownload(url, updateType) {
            let waiting = plus.nativeUI.showWaiting('下载中...')
            // 创建下载任务
            let dtask = plus.downloader.createDownload(
                url,
                {
                    filename: '_doc/update/' // 文件下载保存路径
                },
                (d, status) => {
                    plus.nativeUI.closeWaiting()
                    console.log('createDownload', url)
                    this.installApp(d, status)
                }
            )
            dtask.start()
        },
        installApp(d, status) {
            if (status === 200) {
                plus.nativeUI.showWaiting('安装中...')
                // 下载成功-自动安装
                plus.runtime.install(
                    d.filename,
                    {},
                    () => {
                        plus.nativeUI.closeWaiting()
                        plus.nativeUI.alert('更新完成！', () => {
                            this.updateStatus = false
                            // 清除所有下载的包
                            this.removeRecursively()
                            // 重启app
                            plus.runtime.restart()
                        })
                    },
                    e => {
                        this.removeRecursively()
                        plus.nativeUI.closeWaiting()
                        plus.nativeUI.alert('安装失败[' + e.code + ']：' + e.message, () => {
                            this.updateStatus = false
                        })
                    }
                )
            } else {
                // 下载失败
                plus.nativeUI.alert('下载失败！', () => {
                    this.updateStatus = false
                })
            }
        },
        removeRecursively() {
            plus.io.resolveLocalFileSystemURL('_doc/update/', entry => {
                entry.removeRecursively(() => {
                    //递归删除成功
                    console.log('Remove Recursively Succeeded')
                })
            })
        }
    },

    onShow: function() {
        this.init()
        // console.log('App Show')
    },
    onHide: function() {
        // plus.nativeUI.closeWaiting()
        // console.log('App Hide')
    }
}
</script>

<style lang="scss">
@import '/globe/index.scss';

page {
    // --theme: #4e6ef3;
    --theme: #77c25a;
    --themeHK: #00be5f;
    --backgroundColor: linear-gradient(225deg, #77c25a 0%, #77c25a 100%);
    // --backgroundColor: linear-gradient(225deg, rgba(116, 155, 255, 1) 0%, rgba(65, 100, 244, 1) 100%);
    --backgroundColorHK: linear-gradient(225deg, #72af88 0%, #00be5f 100%);
}
.zh {
    color: var(--theme);
}
.hk {
    color: var(--themeHK);
}
.buttom.zh {
    background-color: var(--theme);
}
.buttom.hk {
    background-color: var(--themeHK);
}
.button.zh {
    background-color: var(--theme);
}
.button.hk {
    background-color: var(--themeHK);
}
.ios-btm {
    height: 20rpx;
    height: constant(safe-area-inset-bottom);
    /* 兼容 iOS < 11.2 */
    height: env(safe-area-inset-bottom);
    /* 兼容 iOS >= 11.2 */
}
</style>
